<template>
  <lay-layer
    v-model="visible"
    title="订单备注"
    :area="['500px', 'auto']"
    :shade="true"
    :shade-close="false"
    :move="true"
  >
    <div class="remark-dialog">
      <div v-if="order" class="order-info">
        <h4>订单信息</h4>
        <div class="order-summary">
          <div class="summary-item">
            <span class="label">订单号：</span>
            <span class="value">{{ order.order_no }}</span>
          </div>
          <div class="summary-item">
            <span class="label">收货人：</span>
            <span class="value">{{ order.consignee_name }}</span>
          </div>
          <div class="summary-item">
            <span class="label">订单状态：</span>
            <lay-tag :type="getOrderStatusType(order.order_status)">
              {{ getOrderStatusText(order.order_status) }}
            </lay-tag>
          </div>
        </div>
      </div>

      <lay-form 
        :model="remarkForm" 
        ref="remarkFormRef"
        :rules="formRules"
        label-width="80px"
      >
        <lay-form-item label="备注类型" prop="remarkType">
          <lay-select 
            v-model="remarkForm.remarkType" 
            placeholder="请选择备注类型"
          >
            <lay-select-option value="customer">客户备注</lay-select-option>
            <lay-select-option value="internal">内部备注</lay-select-option>
            <lay-select-option value="shipping">物流备注</lay-select-option>
            <lay-select-option value="payment">支付备注</lay-select-option>
            <lay-select-option value="other">其他备注</lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="备注内容" prop="content" required>
          <lay-textarea 
            v-model="remarkForm.content" 
            placeholder="请输入备注内容"
            :rows="5"
            :maxlength="500"
            show-count
          />
        </lay-form-item>

        <lay-form-item label="重要程度" prop="priority">
          <lay-radio-group v-model="remarkForm.priority">
            <lay-radio value="low">普通</lay-radio>
            <lay-radio value="medium">重要</lay-radio>
            <lay-radio value="high">紧急</lay-radio>
          </lay-radio-group>
        </lay-form-item>

        <lay-form-item label="是否可见" prop="isVisible">
          <lay-switch 
            v-model="remarkForm.isVisible"
            :switch-text="['是', '否']"
          />
          <div class="form-tip">开启后客户可在订单详情中看到此备注</div>
        </lay-form-item>
      </lay-form>

      <!-- 历史备注 -->
      <div class="history-remarks" v-if="historyRemarks.length > 0">
        <h4>历史备注</h4>
        <div class="remarks-list">
          <div 
            v-for="remark in historyRemarks" 
            :key="remark.id"
            class="remark-item"
          >
            <div class="remark-header">
              <div class="remark-meta">
                <lay-tag 
                  :type="getRemarkTypeColor(remark.remark_type)" 
                  size="xs"
                >
                  {{ getRemarkTypeText(remark.remark_type) }}
                </lay-tag>
                <lay-tag 
                  :type="getPriorityColor(remark.priority)" 
                  size="xs"
                  v-if="remark.priority !== 'low'"
                >
                  {{ getPriorityText(remark.priority) }}
                </lay-tag>
                <span class="remark-time">{{ formatDateTime(remark.created_at) }}</span>
              </div>
              <div class="remark-operator">{{ remark.operator || '系统' }}</div>
            </div>
            <div class="remark-content">{{ remark.content }}</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="dialog-footer">
        <lay-button @click="handleCancel">取消</lay-button>
        <lay-button 
          type="primary" 
          @click="handleConfirm"
          :loading="submitting"
        >
          保存备注
        </lay-button>
      </div>
    </div>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { layer } from '@layui/layer-vue'
import { orderApi, type Order } from '@/api/module/order'

interface Props {
  visible: boolean
  order: Order | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}

interface OrderRemark {
  id: number
  order_id: number
  remark_type: string
  content: string
  priority: string
  is_visible: boolean
  operator: string
  created_at: string
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const submitting = ref(false)
const remarkFormRef = ref()
const historyRemarks = ref<OrderRemark[]>([])

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 备注表单
const remarkForm = reactive({
  remarkType: 'internal',
  content: '',
  priority: 'low',
  isVisible: false
})

// 表单验证规则
const formRules = {
  content: [
    { required: true, message: '请输入备注内容', trigger: 'blur' },
    { min: 5, message: '备注内容至少5个字符', trigger: 'blur' }
  ]
}

// 监听对话框显示状态
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.order) {
    resetForm()
    getHistoryRemarks()
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(remarkForm, {
    remarkType: 'internal',
    content: '',
    priority: 'low',
    isVisible: false
  })
  
  remarkFormRef.value?.clearValidate()
}

// 获取历史备注
const getHistoryRemarks = async () => {
  if (!props.order) return

  try {
    const response = await orderApi.getOrderRemarks(props.order.id)
    if (response.code === 200) {
      historyRemarks.value = response.data
    }
  } catch (error) {
    console.error('获取历史备注失败:', error)
  }
}

// 确认保存
const handleConfirm = async () => {
  if (!props.order) return

  try {
    // 表单验证
    const valid = await remarkFormRef.value?.validate()
    if (!valid) return

    submitting.value = true

    const remarkData = {
      orderId: props.order.id,
      remarkType: remarkForm.remarkType,
      content: remarkForm.content,
      priority: remarkForm.priority,
      isVisible: remarkForm.isVisible
    }

    const response = await orderApi.addOrderRemark(remarkData)
    
    if (response.code === 200) {
      layer.msg('备注保存成功', { icon: 1 })
      emit('refresh')
      getHistoryRemarks() // 刷新历史备注
      resetForm()
    } else {
      layer.msg(response.message || '保存失败', { icon: 2 })
    }
  } catch (error) {
    console.error('保存备注失败:', error)
    layer.msg('保存备注失败', { icon: 2 })
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  visible.value = false
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap = {
    1: 'warm',     // 待付款
    2: 'normal',   // 待发货
    3: 'primary',  // 待收货
    4: 'normal',   // 已完成
    5: 'danger',   // 已取消
    6: 'warm'      // 退款中
  }
  return statusMap[status] || 'primary'
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消',
    6: '退款中'
  }
  return statusMap[status] || '未知'
}

// 获取备注类型颜色
const getRemarkTypeColor = (type: string) => {
  const colorMap = {
    customer: 'primary',
    internal: 'normal',
    shipping: 'warm',
    payment: 'danger',
    other: 'primary'
  }
  return colorMap[type] || 'primary'
}

// 获取备注类型文本
const getRemarkTypeText = (type: string) => {
  const textMap = {
    customer: '客户备注',
    internal: '内部备注',
    shipping: '物流备注',
    payment: '支付备注',
    other: '其他备注'
  }
  return textMap[type] || '未知'
}

// 获取优先级颜色
const getPriorityColor = (priority: string) => {
  const colorMap = {
    low: 'primary',
    medium: 'warm',
    high: 'danger'
  }
  return colorMap[priority] || 'primary'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap = {
    low: '普通',
    medium: '重要',
    high: '紧急'
  }
  return textMap[priority] || '普通'
}
</script>

<style scoped>
.remark-dialog {
  padding: 20px;
}

.order-info {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.order-info h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.order-summary {
  display: grid;
  gap: 8px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.summary-item .value {
  color: #333;
  flex: 1;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  margin-left: 8px;
}

.history-remarks {
  margin: 24px 0;
  padding-top: 16px;
  border-top: 1px solid #e6e6e6;
}

.history-remarks h4 {
  margin: 0 0 16px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.remarks-list {
  max-height: 300px;
  overflow-y: auto;
}

.remark-item {
  padding: 12px;
  margin-bottom: 12px;
  background-color: #f9f9f9;
  border-radius: 6px;
  border-left: 3px solid #1890ff;
}

.remark-item:last-child {
  margin-bottom: 0;
}

.remark-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.remark-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.remark-time {
  font-size: 12px;
  color: #999;
}

.remark-operator {
  font-size: 12px;
  color: #666;
}

.remark-content {
  color: #333;
  line-height: 1.5;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e6e6e6;
}

@media (max-width: 768px) {
  .remark-dialog {
    padding: 16px;
  }
  
  .summary-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .summary-item .label {
    min-width: auto;
    margin-bottom: 4px;
  }
  
  .remark-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>